package finds;

import io.appium.java_client.android.AndroidDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.util.Set;

public class Finder {
    private AndroidDriver<WebElement> driver;
    public Finder(AndroidDriver<WebElement> driver){
        this.driver=driver;
    }
    public boolean waitforWebElement(String id) {
        //根据id来断言当前页面是否跳转
        WebDriverWait wait = new WebDriverWait(driver, 30);
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(id)));
        return true;
    }
    public boolean waitforWebElementForText(String text) {
        //根据id来断言当前页面是否跳转
        WebDriverWait wait = new WebDriverWait(driver, 20);
        wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText(text)));
        return true;
    }
    //切换WebView
    public void switchWebView(){
        Set<String> handleSet = driver.getContextHandles();
        for (String handle : handleSet) {
            System.out.println("===" + handle);
        }

        String last = handleSet.toArray()[handleSet.toArray().length - 1].toString();
        if (last.contains("WEBVIEW")) {
            driver.context(last);
        }

    }
    //根据id找元素
    public WebElement findElementById(String id){
        return driver.findElementById(id);
    }
    //有多个相同id的控件时查找元素
    public WebElement findElementsById(String id,int index){
        return driver.findElementsById(id).get(index);
    }
    //滑动列表（从上到下滑动）
    public void scrollList(int count){
        //获取屏幕宽高
      for(int c=0;c<=count;c++){
          int x=driver.manage().window().getSize().width;
          int y=driver.manage().window().getSize().height;
          driver.swipe(x/2,y*3/4,x/2,y*1/4,2000);
      }
    }
    //根据text属性查找
    public WebElement findElementByText(String text){
        return driver.findElementByName(text);
    }
    //根据classname属性查找
    public WebElement findElementsByClassName(String classname,int index){
        return driver.findElementsByClassName(classname).get(index);
    }
    //根据xpath路径查找
    public WebElement findElementByXpath(String xpath){
        return driver.findElementByXPath(xpath);
    }
    //判断元素是否存在
    public boolean isElementExist(By id) {
        try {
            driver.findElement(id);
            return true;
        } catch (org.openqa.selenium.NoSuchElementException ex) {
            return false;
        }
    }
}
